var depth,
    depthid,
    attributename,
    attributeid,
    quantity,
    tags;

$(document).ready(function() {
    // hide edit and remove button at first load,
    // show this on edit mode only, otherwise show add button
    $("#edit-attribute").hide();

    // dont show delete button on new depth
    if (getParamValue(window.location.href, "depth") == 'new') {
        $("#delete-depth").hide();
    }

    /**
    * form processor
    */
    depth = $("#observationdepth_observationdepth"),
    depthid = $("#observationdepthattribute_observationdepthid"),
    attributeid = $('#observationdepthattribute_attributeid'),
    attributevalue = $('#observationdepthattribute_attributevalue'),
    unit = $('#unit_unit'),
    unitid = $('#unit_id'),
    odaid = $('#observationdepthattribute_id'),
    allfields = $([]).add(attributeid).add(attributevalue).add(unit);


    /**
     * save changes to list
     */
    $("#save-attribute").button().click(function(){
        addToList();
    });

    /*
     * edit a row
     */
    $("#edit-attribute").button().click(function(){
        var formObj = createObjectForm();
        formObj.id = odaid.val();

        saveAttribute(formObj, 'edit');

        allfields.val( "" ).removeClass( "ui-state-error" );
        toggleButton('add');
    });

    $("#clear-form").button().click(function(){
        clearForm();
    });

    // delete depth
    $("#delete-depth").button({
        icons: {primary: "ui-icon-close"}, text: false
    })
    .click(function(){
        window.location = "/data/deleteDepth/obs/" +
            getParamValue(window.location.href, "obs") + "/" +
            "depth/" + getParamValue(window.location.href, "depth");
    });

    // only show button save on editing depth value
    if (depth.val() == "")  $("#update-depth").hide();

    // update depth handler
    $("#update-depth").button({
        icons: {primary: "ui-icon-pencil"}, text: false
    }).click(function(){

        if ($(this).attr('title') == "Edit depth") {
            // edit mode
            $(this).attr('title', 'Save');
            depth.attr('readonly', false);
            depth.css('border-color', '#96B7E9');
            depth.css('color', '#312E25');
            $(this).button('option', 'icons', {primary: 'ui-icon-disk'});
            $(this).button('option', 'label', 'Save');
        } else {
            // update mode
            if (updateDepth()) {
            }
        }

    });

    prepareUnits(attributeid.val(), null);

    // add unit
    $("#add_unit").button({
        icons: {primary: "ui-icon-plus"}, text: false
    });

    // add attribute
    $("#add_attribute_btn").button({
        icons: {primary: "ui-icon-plus"}, text: false
    });
});

function addToList() {
    allfields.removeClass( "ui-state-error" );
    depth.removeClass( "ui-state-error" );

    var formObj = createObjectForm();
    var success = saveAttribute(formObj, 'add');   // implemented in _attributeList.php
    if (success)
        allfields.val( "" ).removeClass( "ui-state-error" );
}

function clearForm() {
    allfields.val( "" ).add(depth).add($('#validate-tip')).removeClass( "ui-state-error" );
    $('#validate-tip').text("");
    $('#validate-tip').hide();
    unit.clearOptions();
    prepareUnits(attributeid.val(), null);
    toggleButton('add');
}

function prepareUnits(attrid, selected) {
    $.ajax({
        type: 'get',
        url: $("#attribute-form").attr('action') + 'getObjectUnit/id/' + attrid + '/type/attribute',
        dataType: "json",
        success: function(data, textStatus, jqXHR) {
            if (data==null) return false;

            $('#unit_unit').clearOptions();
            $('#unit_unit').buildOptions(data, selected);
            $('#unit_unit').append("<option value = 'all'>Show all units</option>");

            return true;
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("error: " + textStatus + ", " + errorThrown);
            return false;
        }
    });
}

function createObjectForm(){
    var formObj = new Object;

    formObj.depthid = depthid.val();
    formObj.depth = depth.val();

    $('#observationdepthattribute_attributeid option:selected').each(function(){
         formObj.attributename = $(this).text();
         formObj.attritbuteid = $(this).val();
    });

    formObj.attributevalue = attributevalue.val();
    $('#unit_unit option:selected').each(function(){
        formObj.unit = $(this).text();
        formObj.unitid = $(this).val();
    })

    formObj.obsid = getParamValue(window.location.href, "obs");

    return formObj;
}

function editForm(id){

    if (id == '') return;

//        attributename.val($("#oda_name_"+id).html());
    attributevalue.val($("#oda_value_"+id).html());
    var attributeName = $("#oda_name_"+id).html();
    $('#observationdepthattribute_attributeid option').each(function(){
        this.selected = (this.text == attributeName);
    });
    prepareUnits(attributeid.val(), $("#oda_unit_"+id).html());

    odaid.val(id);

    toggleButton('edit');
}

function toggleButton(method){
    if (method == 'add') {
        $("#edit-attribute").hide();
        $("#save-attribute").show();
    } else { //edit mode
        $("#edit-attribute").show();
        $("#save-attribute").hide();
    }
}

function updateDepth() {
    var succeed = $.ajax({
        type: 'post',
        url: "/data/updateDepth",
        data: {depthForm: $("#attribute-form").serializeArray()},
        dataType: "html",
        success: function(data, textStatus, jqXHR) {
            location.reload(true);
            return true;
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("error: " + textStatus + ", " + errorThrown);
            return false;
        }
    });

//        alert(succeed);

    return true;
}

function showAttributeForm() {
//    var species_input = "<input type='text' id='new_attribute_input' class='ui-widget ui-widget-content ui-corner-all'/>";
//    var unit_select = "<input type='text' class='ui-widget ui-widget-content ui-corner-all' id = 'unit_id'/>";

    var dialogOptions = {
        title: "Add new attribute",
        closeOnEscape: true,
        position: 'center',
        width: '350px',
        buttons: {
            "Save": function() {
                insertNewAttribute();
            },
            "Cancel": function() {
                $(this).dialog("close");
            }
        }
    }

    if ($("#new_attr_form").exists()){
        $("#attr_new_input").val("");
        $("#unit_new").val("");
        $("#attr_form_msg").html("").hide();
//        $("#new_attr_form").dialog(dialogOptions);
        $("#new_attr_form").parents('.ui-dialog').show();
        return;
    }

    var dialog = $("<div id='new_attr_form'></div>").appendTo('body');
    dialog.load('/data/newAttributeForm', {},
        function(responseText, textStatus, XMLHttpRequest){
            dialog.dialog(dialogOptions);
//            dialog.dialog("open");
        });
    
}

function insertNewAttribute() {
    var mesg;
    var isvalid = true;
    var attr = $("#attr_new_input").val();
    var unit = $("#unit_new").val();

    isvalid = attr != "" && unit != "";

    if (!isvalid) {
        mesg = "Name and unit must not be empty";
        $("#attr_form_msg").html(mesg).show();
        return;
    }

    $.post('/data/createAttribute', {attribute: attr, unit: unit},
        function(data) {
            // returned data is attribute id, or false
            if (data) {
                alert(data);
                $("#new_attr_form").parents('.ui-dialog').hide();
                // reload attribute and unit
                attributeid.loadAttribute(attr, function() {prepareUnits(data, unit)});
//                loadExtendedUnits('all', unit);
            } else {
                mesg = "Attribute already exists";
                $("#attr_form_msg").html(mesg).show();
            }
        }, 'html');
}

$.fn.prepareUnitAutocomplete = function() {
    
    var cache = {}, lastXhr;

    $(this).autocomplete({
        delay: 0,
        source: function (request, response) {
            var term = request.term;
            if (term in cache) {
                response(cache[term]);
                return;
            }

            lastXhr = $.ajax({
                type: "GET",
                url: "/data/searchUnit",
                data: {
                    term: term,
                    maxRows: 40
                },
                dataType: "json",
                success: function(data, textStatus, jqXHR){
                    cache[ term ] = data;

                    if (data.length == 0) {
                        lastUnitFound = "";
                    } else lastUnitFound = data[0].label;

                    response( data );

                    return false;
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    alert("error: " + textStatus + ", " + errorThrown);
                    return false;
                }
            });
        },
        focus: function(event, ui) {
            $(this).val(ui.item.label);
        },
        select: function(event, ui) {
            event.preventDefault();
            $(this).val(ui.item.label);
        }
    })
}

$.fn.loadAttribute = function(selected, callback) {
    var caller = $(this);
    $.get('/data/getAttribute', {}, function(data){
        caller.clearOptions();
        caller.buildOptions(data, selected);
        if (typeof callback == "function") {
            callback.call(this, data);
        }
    }, 'json');
}